package com.goods.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.OutStockService;
import com.goods.business.service.ProductService;
import com.goods.common.enums.buisiness.StatusEnum;
import com.goods.common.model.business.*;
import com.goods.common.response.ActiveUser;
import com.goods.common.vo.business.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description：
 * @version:
 * @author：ruixinag
 * @create：Created in 2021/11/9 16:54
 */
@Service
public class OutStockServiceImpl implements OutStockService {
    @Autowired
    private OutStockMapper outStockMapper;
    @Autowired
    private OutStockInfoMapper outStockInfoMapper;
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ConsumerMapper consumerMapper;

    //1.出库单（发放记录）数据分页列表展示
    @Override
    public Map findOutStockList(Map paramMap) {
        String pageNum = (String) paramMap.get("pageNum");
        String pageSize = (String) paramMap.get("pageSize");
        String status = (String) paramMap.get("status");  //状态
        String outNum = (String) paramMap.get("outNum");  //编号
        String type = (String) paramMap.get("type");      //类型

        //构造查询条件
        Example example = new Example(OutStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",status);
        if(outNum!=null && !"".equals(outNum)){
            criteria.andLike("outNum","%"+outNum+"%");
        }
        if(type!=null && !"".equals(type)){
            criteria.andEqualTo("type",type);
        }
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<OutStock> outStocks = outStockMapper.selectByExample(example);
        PageInfo<OutStock> pageInfo = new PageInfo<>(outStocks);

        List<OutStockVO> list = pageInfo.getList().stream().map(outStock -> {
            OutStockVO outStockVO = new OutStockVO();
            BeanUtils.copyProperties(outStock, outStockVO);
            //获取去向信息
            Consumer consumer = consumerMapper.selectByPrimaryKey(outStock.getConsumerId());
            BeanUtils.copyProperties(consumer,outStockVO, "id");
            return outStockVO;
        }).collect(Collectors.toList());

        Map result=new HashMap<>();
        result.put("rows",list);
        result.put("total",pageInfo.getTotal());

        return result;
    }

    //2.查看出库明细
    @Override
    public OutStockDetailVO detail(Integer pageNum, Long outStackId) {
        //1.先获取出库单
        OutStock outStock = outStockMapper.selectByPrimaryKey(outStackId);

        OutStockDetailVO outStockDetailVO = new OutStockDetailVO();
        BeanUtils.copyProperties(outStock, outStockDetailVO);
        //2.根据out_num查对应的out_stock_info的p_num的数据
        Example example = new Example(OutStockInfo.class);
        example.createCriteria().andEqualTo("outNum",outStock.getOutNum());
        //分页插件
        PageHelper.startPage(pageNum, 10);
        List<OutStockInfo> outStockInfos = outStockInfoMapper.selectByExample(example);
        PageInfo<OutStockInfo> pageInfo = new PageInfo<>(outStockInfos);
        //查对应的product数据
        List<OutStockItemVO> outStockItemVOList = outStockInfos.stream().map(outStockInfo -> {
            OutStockItemVO outStockItemVO = new OutStockItemVO();
            outStockItemVO.setCount(outStockInfo.getProductNumber());
            //根据p_num查product的信息
            Example o = new Example(Product.class);
            o.createCriteria().andEqualTo("pNum", outStockInfo.getPNum());
            //数据库中查对应的物资
            Product product = productMapper.selectOneByExample(o);
            BeanUtils.copyProperties(product, outStockItemVO);
            return outStockItemVO;
        }).collect(Collectors.toList());
        outStockDetailVO.setItemVOS(outStockItemVOList);
        //获取数据的总数
        outStockDetailVO.setTotal(pageInfo.getTotal());
        //3.根据consumer_id,查去处的信息
        Consumer consumer = consumerMapper.selectByPrimaryKey(outStock.getConsumerId());
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer,consumerVO);
        outStockDetailVO.setConsumerVO(consumerVO);
        return outStockDetailVO;
    }

    //新增出库单
    @Override
    public void addOutStock(OutStockVO outStockVo) {
        OutStock outStock = new OutStock();
        BeanUtils.copyProperties(outStockVo, outStock);
        //1.先判断consumer是新增还是已存在
        if(null!=outStockVo.getConsumerId()&& !StringUtils.isEmpty(outStockVo.getConsumerId())){
            //已有的consumer
            outStock.setConsumerId(outStockVo.getConsumerId());
        }else {
            //新增consumer
            Consumer consumer = new Consumer();
            BeanUtils.copyProperties(outStockVo, consumer);
            consumer.setCreateTime(new Date());
            consumer.setModifiedTime(new Date());
            consumerMapper.insertSelective(consumer);
            outStock.setConsumerId(consumer.getId());
        }
        //2.新增outStock
        //2.1 设置out_num
        String uuid = UUID.randomUUID().toString();
        String outNum = uuid.replace("-", "");
        outStock.setOutNum(outNum);
        //2.2 获取当前用户
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        outStock.setOperator(activeUser.getUser().getUsername());
        //2.3 设置状态
        outStock.setStatus(2);
        outStock.setProductNumber(outStockVo.getProducts().size());
        outStock.setCreateTime(new Date());
        outStockMapper.insertSelective(outStock);
        //3.新增outStockInfo
        List<Object> products = outStockVo.getProducts();
        products.stream().forEach(productMap -> {
            Map<String,Integer> map=(Map)productMap;
            OutStockInfo outStockInfo = new OutStockInfo();
            outStockInfo.setOutNum(outStock.getOutNum());
            outStockInfo.setProductNumber(map.get("productNumber"));

            //根据 product_id,查出p_num
            Product product = productMapper.selectByPrimaryKey(map.get("productId"));
            outStockInfo.setPNum(product.getPNum());
            outStockInfo.setCreateTime(new Date());
            outStockInfo.setModifiedTime(new Date());
            outStockInfoMapper.insertSelective(outStockInfo);
        });

    }
    @Autowired
    private ProductStockMapper productStockMapper;

    //审核通过,增加库存,由于前端控制了库存的最大量,不用考虑不够减的问题
    @Override
    public void publish(Long outStockId) {
        //1.根据id查出库表
        OutStock outStock = outStockMapper.selectByPrimaryKey(outStockId);
        //2.根据out_num,取outStockInfo查出对应的商品的pNum和数量
        Example example = new Example(OutStockInfo.class);
        example.createCriteria().andEqualTo("outNum",outStock.getOutNum());
        List<OutStockInfo> outStockInfoList = outStockInfoMapper.selectByExample(example);
        outStockInfoList.stream().forEach(outStockInfo -> {
            //3.取库存表减库存
            Example o = new Example(ProductStock.class);
            o.createCriteria().andEqualTo("pNum",outStockInfo.getPNum());
            ProductStock productStock = productStockMapper.selectOneByExample(o);
            productStock.setStock(productStock.getStock()-outStockInfo.getProductNumber());
            productStockMapper.updateByPrimaryKey(productStock);
        });
        //4.更改出库表状态
        outStock.setStatus(StatusEnum.NORMAL.getCode());
        //5.更新出库表数据
        outStockMapper.updateByPrimaryKey(outStock);



    }

    //移动至回收站
    @Override
    public void remove(Long outStockId) {
        OutStock outStock = outStockMapper.selectByPrimaryKey(outStockId);
        //更改出库表状态
        outStock.setStatus(1);
        //更新出库表数据
        outStockMapper.updateByPrimaryKey(outStock);
    }

    //还原
    @Override
    public void back(Long outStockId) {
        OutStock outStock = outStockMapper.selectByPrimaryKey(outStockId);
        //更改出库表状态
        outStock.setStatus(StatusEnum.RECYCLE.getCode());
        //更新出库表数据
        outStockMapper.updateByPrimaryKey(outStock);
    }

    //删除
    @Override
    public void delete(Long outStockId) {
        outStockMapper.deleteByPrimaryKey(outStockId);
    }

}
